'''
Created on 2014-04-10

@author: masinko
'''
import commonutils as common
from appmanager import AppManager
from appmanager import Mode
import os
import urlresolver

class DireTube:
    
    _main_url = ''
    _name = 'DireTube'
    _icon_path = str(os.path.dirname(os.path.realpath(__file__))) + '/../icons/diretube/'
    _fanart_path = str(os.path.dirname(os.path.realpath(__file__))) + '/../fanarts/diretube/'

    def __init__(self,app_manager):
       _main_url = 'http://www.diretube.com/index.html'
       self.app = app_manager
       
    def getName(self):
        return DireTube._name
    
    def getIcon(self):
        return DireTube._icon_path + 'main.png'
    
    def getNextPageIcon(self):
        return DireTube._icon_path + 'nextpage.png'
       
    def getFanart(self):
        return DireTube._fanart_path + 'main.jpg'
    
    def getCategoryFanart(self):
        return DireTube._fanart_path + 'categoryfanart.jpg'
    
    def getSubMenuFanart(self):
        return DireTube._fanart_path + 'submenufanart.jpg'
        
    
    def displayMainMenu(self):
        import time
        start = time.clock()
        mainSrc = common.urlReader('http://www.diretube.com/index.html')
        print '-----reading url took '
        print time.clock() - start
        print 'getting category'
        match = self.getCategoryList(mainSrc)
        for eachmatch in match:
            category = eachmatch[-1]
            link = eachmatch[0] 
            start1 = time.clock()
            total_page = 1#self.getNumberOfPagesForCategory(link)
            print '-----reading Category page url took ' 
            print time.clock() - start1
            currentCategory = category
            start2 = time.clock()
            self.app.getAddon().add_directory({'mode': Mode.SUBMENUSELECTED, 'name': self.getName(), 'url': link, 'categoryPage': link, 'category': category, 'page_num': 1, 'total_page': total_page}, {'title': category}, img='newtv.png',fanart=self.getCategoryFanart())
            print '-----adding dir took ' 
            print time.clock() - start2
            
    def displaySubMenu(self):
        page_url = self.app.getURL()
        self.populateMediaList(page_url)
        total_pages = self.getNumberOfPagesForCategory(page_url)
        self.app.getAddon().add_directory({'mode': Mode.NEXT, 'name': self.getName(), 'url': page_url, 'page_num': 1, 'total_pages': total_pages}, {'title': '1 of ' + str(total_pages)+ ' Next Page >>>'}, img=self.getNextPageIcon())
           
    def displayNextPage(self):
        page_num = self.app.getAddonQueries('page_num')
        cur_page = int(page_num) + 1
        url = self.app.getURL()
        page_url = url[:-11] + str(cur_page) + '-date.html'
        print 'page url is -----------'
        print page_url
        self.populateMediaList(page_url)
        total_pages = self.app.getAddonQueries('total_pages')
        if int(cur_page) < int(total_pages):
            self.app.getAddon().add_directory({'mode': Mode.NEXT, 'name': self.getName(), 'url': page_url, 'page_num': cur_page, 'total_pages': total_pages}, {'title': str(cur_page) + ' of ' + str(total_pages)+ ' Next Page >>>'}, img=self.getNextPageIcon())
       
    def getCategoryList(self,page):
        start = '<h3 class="captions">Category</h3>'
        end = '<h3 class="captions">Members</h3>'
        category = common.extractSubString(page,start,end)
        print 'category is --->'
        #print category
        match = common.find('<a href="(.+?)">(.+?)</a>', category)
        print 'match is ---->'
        #print match
        return match

    def getNumberOfPagesForCategory(self,url):
        src = common.urlReader(url)
        match = common.find('<meta name=.*Page(.+?)".* />', src)    
        return int(match[0].split()[-1])
  
    def getBrowseListForPage(self, pageUrl):
        start = '<div id="browse_results">'
        end = '/* BrowseVideoBelow */'
        src = common.urlReader(pageUrl)
        browse_result = common.extractSubString(src,start,end)
        match = common.find('<a href="(.+?)">\s*<img src="(.+?)"  alt=.*\s*</a>\s*.*\s*<span class="artist_name">(.+?)</span> <span class="song_name">(.+?)</span>', browse_result)
        return match
    
    def populateMediaList(self,page_url):
        match = self.getBrowseListForPage(page_url)
        print match
        for eachmatch in match:
            link = eachmatch[0]
            icon = eachmatch[1]
            title = eachmatch[2] + '-' + eachmatch[3]
            videoPage = common.extractSubString(common.urlReader(link),'var flashvars = {','jwplayer("Playerholder").setup(flashvars);',14000)
            matchLink = common.find('file:\s*\'(.+?)\'', videoPage)
            if len(matchLink) < 1:
                videoPage = common.extractSubString(common.urlReader(link),'<div id=\"Playerholder\">','<div class=\"tag_featured\">')
                matchLink = common.find('<iframe width=".*" height=".*" src=".*(www.+?)" frameborder=".*" allowfullscreen></iframe>', videoPage)
            print 'matchLink'
            print matchLink
            if len(matchLink) > 0 :
                videoLink = matchLink[0]
                print 'videoLink ---- is'
                print videoLink
                d = 22 - len(videoLink)
                if 'http://www.youtube.com' == videoLink[:d]:
                    media = urlresolver.HostedMediaFile(videoLink)
                    videoLink = media.resolve()
                    print videoLink
                self.app.getAddon().add_video_item({'mode': Mode.PLAY, 'url': videoLink}, {'title': title}, img=icon,fanart=self.getSubMenuFanart())
    '''
    def nextPage():
        cur_page = int(page_num) + 1
        page_url = url[:-11] + str(cur_page) + '-date.html'
        print 'page url is -----------'
        print page_url
        populateMediaList(page_url)
        addon.add_directory({'mode': 'Next', 'currentCategory': currentCategory, 'url': page_url, 'page_num': cur_page, 'total_page': total_page}, {'title': 'Next Page>>>'}, img='newtv.png')
    
    def categorySelected():
        page_url = url
        populateMediaList(page_url)
        addon.add_directory({'mode': 'Next', 'currentCategory': currentCategory, 'url': page_url, 'page_num': 1, 'total_page': total_page}, {'title': 'Next Page>>>'}, img='newtv.png')
  
    '''    
